package org.framework.customutil;

import java.net.URL;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

/**
 * @Title: EhcacheUtil.java .<br>
 * @Package org.framework.customutil .<br>
 * @Description: 缓存工具类，配置在config目录下（config/ehcache.xml） .<br>
 * @author 郑成功 .<br>
 * @email a876459952@qq.com .<br>
 * @date 2018-6-7 下午9:38:32.<br>
 * @version V1.0.<br>
 */
public class EhcacheUtil {
	
	private static final String path = "config/ehcache.xml";  
	
	
	private static final URL url = EhcacheUtil.class.getClassLoader().getResource(path);      

	public static CacheManager manager = CacheManager.create(url);

	/**
	 * @Description: 获取缓存里面的值 .<br>
	 * @param cacheName 缓存名称.<br>
	 * @param key 对应的key.<br>
	 * @author 郑成功 .<br>
	 * @date 2018-6-7 下午9:40:52.<br>
	 */
	public static Object get(String cacheName, Object key) {
		Cache cache = manager.getCache(cacheName);
		if (cache != null) {
			Element element = cache.get(key);
			if (element != null) {
				return element.getObjectValue();
			}
		}
		return null;
	}

	/**
	 * @Description: 加入缓存 .<br>
	 * @param cacheName 缓存名称.<br>
	 * @param key 对应的key.<br>
	 * @param value 对应的值.<br>   
	 * @author 郑成功 .<br>
	 * @date 2018-6-7 下午9:40:22.<br>
	 */
	public static void put(String cacheName, Object key, Object value) {
		Cache cache = manager.getCache(cacheName);
		if (cache != null) {
			cache.put(new Element(key, value));
		}
	}

	/**
	 * @Description: 移除指定的数据 .<br>
	 * @param cacheName 缓存名称.<br>
	 * @param key 对应的key.<br>
	 * @author 郑成功 .<br>
	 * @date 2018-6-7 下午9:39:38.<br>
	 */
	public static boolean remove(String cacheName, Object key) {
		Cache cache = manager.getCache(cacheName);
		if (cache != null) {
			return cache.remove(key);
		}
		return false;
	}
	
	/**
	 * @Description: 测试缓存 .<br>
	 * @param args .<br>   
	 * @author 郑成功 .<br>
	 * @date 2018-6-7 下午9:39:25.<br>
	 */
	public static void main(String[] args) {
		String key = "key";
		String value = "hello";
		EhcacheUtil.put("mytest", key, value);
		System.out.println(EhcacheUtil.get("mytest", key));
	}

}